<template>
  <div class="upload-excel">
    <!-- 文件选择框: 默认隐藏，当点击上传按钮触发文件选择框的点击 -->
    <input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx, .xls" @change="handleClick">

    <!-- 点击上传 -->
    <div class="btn-upload">
      <el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
        文件上传按钮
      </el-button>
    </div>

    <!-- 拖拽上传
         dragenter拖拽元素进入盒子了（阻止冒泡，阻止默认行为做兼容）
         dragover拖拽元素在盒子上晃（阻止冒泡，阻止默认行为做兼容）

         drop 拖拽元素在盒子上，松手了（核心）
    -->
    <div class="drop" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
      <i class="el-icon-upload" />
      <span>将文件拖拽到此处</span>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'

export default {
  props: {
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function// eslint-disable-line
  },
  data() {
    return {
      loading: false,
      excelData: {
        header: null,
        results: null
      }
    }
  },
  methods: {
    generateData({ header, results }) {
      this.excelData.header = header
      this.excelData.results = results

      // 判断有没有配置success函数，如果有，将得到的结果作为参数传递给success
      this.onSuccess && this.onSuccess(this.excelData)
    },
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      if (this.loading) return
      const files = e.dataTransfer.files
      if (files.length !== 1) {
        this.$message.error('Only support uploading one file!')
        return
      }
      const rawFile = files[0] // only use files[0]

      if (!this.isExcel(rawFile)) {
        this.$message.error('Only supports upload .xlsx, .xls, .csv suffix files')
        return false
      }
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      // this.$refs.myinput.click()
      // this.$refs['myinput'].click()
      this.$refs['excel-upload-input'].click()
    },
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]

      // 看看有没有选择文件，如果没有选中文件，直接return
      if (!rawFile) return

      // 选中了文件，再开始上传
      this.upload(rawFile)
    },
    upload(rawFile) {
      // 开始解析处理这个文件后，清空输入框中已选的文件value，保证重复选中同一个文件
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel

      // 如果没有配置上传前的校验函数，表示不校验
      if (!this.beforeUpload) {
        // 直接读取文件，进行excel解析
        this.readerData(rawFile)
        return
      }

      // beforeUpload的返回值
      // 1. return true 通过校验
      // 2. return false 不通过校验
      const before = this.beforeUpload(rawFile)

      // 判断是否需要读取文件
      if (before) {
        this.readerData(rawFile)
      }
    },
    readerData(rawFile) {
      // 一旦开始读取文件，立刻 loading = true 节流
      this.loading = true
      return new Promise((resolve, reject) => {
        // FileReader html5 新增的文件读取API，可以读取文件
        const reader = new FileReader()
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet)

          // 将读取得到的 header【excel的头】 和 results【整个excel的列表数据】返回
          this.generateData({ header, results })

          // 读取文件完成了，将 loading 改成 false
          this.loading = false
          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name)
    }
  }
}
</script>

<style scoped lang="scss">
.upload-excel {
  display: flex;
  justify-content: center;
  margin-top: 100px;
  .excel-upload-input {
    display: none;
    z-index: -9999;
  }
  .btn-upload,
  .drop {
    border: 1px dashed #bbb;
    width: 350px;
    height: 160px;
    text-align: center;
    line-height: 160px;
  }
  .drop {
    padding-top: 20px;
    line-height: 80px;
    color: #bbb;
    i {
      font-size: 60px;
      display: block;
    }
  }
}
</style>
